/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.chat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.service.JaberClientService;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.UserInfoActivity;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 
 * 在线用户列表
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class UserListActivity extends Activity implements OnItemClickListener
{
    private ListView listView;
    //private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private ArrayList<UserInfo> list = new ArrayList<UserInfo>();
    //private List<UserInfo> users = new ArrayList<UserInfo>();
    private TreeMap<Integer, UserInfo> users = new TreeMap<Integer, UserInfo>();
    private MyAdapter myAdapter;
    private ProgressDialog progressDialog = null;
    private boolean success=false;
    private DolphinApplication app;
    private JaberClientService jaberClientService;
    private AsynLoad anseylodar;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friend_list);
        app = (DolphinApplication)getApplication();
        anseylodar=new AsynLoad();//异步加载头像
        jaberClientService = JaberClientService.getInstance();
        listView = (ListView)findViewById(R.id.friend_list);
        listView.setOnItemClickListener(this);
        myAdapter = new MyAdapter(this);
        listView.setAdapter(myAdapter);
        //findFriends();
        //myAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onStart()
    {
        super.onStart();
        //页面打开时，请求用户数据并显示出来
        progressDialog = ProgressDialog.show(this.getParent(), "请稍等...", "正在加载用户数据...", true);
        new GetUserTask().execute(null);
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id)
    {
        Collection<UserInfo> values = users.values();
        list.clear();
        list.addAll(values);
        UserInfo user = list.get(position);
        Integer userId = user.getUserId();
        LogUtil.d("发送的userId: "+userId);
        Intent intent = new Intent(this,UserInfoActivity.class);
        intent.putExtra("userId", String.valueOf(userId));
        intent.putExtra("from", "user");
        startActivity(intent);
    }
    
    
    
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;
        private Map<Integer,View> map;
        
        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
            map = new HashMap<Integer, View>();
        }
        
        public int getCount()
        {
            return users.size();
        }
        
        public Object getItem(int position)
        {
            return null;
        }
        
        public long getItemId(int position)
        {
            return 0;
        }
        
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View rowView = map.get(position);
            ViewHolder holder = null; 
            if (rowView == null)
            {
                holder = new ViewHolder();
                rowView = mInflater.inflate(R.layout.friend_item, null);
                holder.imgHead = (ImageView)rowView.findViewById(R.id.img_head);
                holder.tvUserName = (TextView)rowView.findViewById(R.id.tv_user_name);
                //holder.tvPoint = (TextView)rowView.findViewById(R.id.tv_point);
                holder.tvRemark = (TextView)rowView.findViewById(R.id.tv_user_remark);
                rowView.setTag(holder);
                map.put(position, rowView);
            }
            else
            {
                holder = (ViewHolder)rowView.getTag();
            }
            
            Collection<UserInfo> values = users.values();
            list.clear();
            list.addAll(values);
            UserInfo user = list.get(position);
            //String userName = map.get(Friend.C_USER_NAME);
            holder.tvUserName.setText(user.getUserName());
            holder.tvRemark.setText(user.getRemark());
            holder.imgHead.setTag(RequestUtils.IMG_URL+user.getUserId()+".jpg");
            anseylodar.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+user.getUserId()+".jpg");//异步加载图片
            return rowView;
        }
        class ViewHolder
        {
            public ImageView imgHead;
            public TextView tvUserName;
            public TextView tvPoint;
            public TextView tvRemark;
        }
    }
    class GetUserTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            if(!RequestUtils.getInstall().isConnect(UserListActivity.this))
            {
                return "网络不可用";
            }
            String json = null;
            try
            {
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                
                param.add(new BasicNameValuePair("orderby","0"));//查询条件[0：按积分排序；1：按用户名排序]
                
                json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"user/getOnlineUser.php", param);
                if(json != null)
                {
                    success=true;
                }
                
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
                return "请求失败，请稍候再试";
            }
            return json;
            
        }
        
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(!success)
            {
                Toast.makeText(UserListActivity.this, result, Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                return;
            }
            try
            {
                JSONObject data = new JSONObject(result);
                String msgCode = data.getString("msgCode");
                String desc = data.getString("desc");
                if("1".equals(msgCode))
                {
                    JSONObject pageBean = data.getJSONObject("msgBody");
                    JSONArray jsonArray = pageBean.getJSONArray("elements");
                    int len = jsonArray.length();
                    for (int i = 0; i < len; i++)
                    {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Integer id = Integer.valueOf(object.getString("userId"));
                        //过滤掉自己
                        if(!id.equals(app.getUserId()))
                        {
                            UserInfo user = new UserInfo();
                            user.setUserId(id);
                            user.setUserName(object.getString("userName"));
                            user.setAccount(object.getString("account"));
                            user.setHeadPic(object.getString("headPic"));
                            user.setPoint(Integer.valueOf(object.getString("point")));
                            user.setRemark(object.getString("remark"));
                            user.setUserTitle(object.getString("userTitle"));
                            users.put(id, user);
                        }
                        
                    }
                    myAdapter.notifyDataSetChanged();
                }else
                {
                    Toast.makeText(UserListActivity.this, desc, Toast.LENGTH_LONG).show();
                    LogUtil.d(desc);
                }      
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
            }
            //关闭进度条窗口
            progressDialog.dismiss();      
        }
        
    }
}
